﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Core.Business;

namespace TicketManagement.Ticket
{
    public partial class TicketEdit : System.Web.UI.Page
    {
        private TicketBus bus = new TicketBus();
        private TicketCommentBus commentBus = new TicketCommentBus();
        private Core.Entity.Ticket ticket = new Core.Entity.Ticket();

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                int id = int.Parse(Request.QueryString["id"].ToString());
                ticket = bus.get(id);
            }
            catch (Exception ex) { }
            if (!IsPostBack)
            {
                loadStatus();
                loadSatff();
                showData();
                showComments();
            }
        }

        public void showData()
        {
            lblTicketNumber.InnerText = ticket.Number;

            ServiceBus serviceBus = new ServiceBus();
            Core.Entity.Service service = serviceBus.getByServiceType(ticket.ServiceTypeId);

            OrderLineBus orderLineBus = new OrderLineBus();
            Core.Entity.OrderLine orderLine = orderLineBus.get(ticket.OrderLineId);

            lblService.InnerText = service.Name + ": " + orderLine.Desc;

            cmbStatus.SelectedValue = ticket.TicketStatusId.ToString();

            TicketCategoryBus catBus = new TicketCategoryBus();
            Core.Entity.TicketCategory cat = new Core.Entity.TicketCategory();
            cat = catBus.get(ticket.TicketCategoryId);
            lblRequireType.InnerText = cat.Name;

            DepartmentBus depBus = new DepartmentBus();
            Core.Entity.Department dep = depBus.get(ticket.DepartmentId);
            lblDepartment.InnerText = dep.Name;

            cmbStaff.SelectedValue = ticket.StaffId.ToString();

            lblSubject.InnerText = ticket.Subject;
            lblContent.InnerHtml = ticket.Content;
            if (ticket.Attachment != "")
            {
                lblAttachment.InnerHtml = "Hình minh họa: <a href='/Assets/data/" + ticket.Attachment + "' target='_blank'>" + ticket.Attachment + "</a>";
            }
        }

        public void loadStatus() {
            TicketStatusBus statusBus = new TicketStatusBus();
            List<Core.Entity.TicketStatus> statuses = statusBus.getAll();
            cmbStatus.DataSource = statuses;
            cmbStatus.DataBind();
        }

        public void loadSatff() {
            StaffBus staffBus = new StaffBus();
            List<Core.Entity.Staff> staffs = staffBus.getAll();
            cmbStaff.DataSource = staffs;
            cmbStaff.DataBind();
        }

        private void showComments()
        {
            List<Core.Entity.TicketComment> comments = commentBus.getAll(ticket.Id);
            rptComments.DataSource = comments;
            rptComments.DataBind();
        }

        public void update() {
            if (ticket.Id > 0) {
                ticket.TicketStatusId = int.Parse(cmbStatus.SelectedValue);
                ticket.StaffId = int.Parse(cmbStaff.SelectedValue);
            }

            if (bus.update(ticket))
            {
                String script = "alert('Cập nhật thành công!'); location.href='/Ticket/AllTicket.aspx';";
                ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", script, true);
            }
            else
            {
                lblMessage.InnerText = "Không cập nhật được. Vui lòng thử lại.";
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.update();
        }

        protected void btnDeleteTicket_Click(object sender, EventArgs e)
        {
            commentBus.deleteByTicket(ticket.Id);
            bus.delete(ticket.Id);
            Response.Redirect("/Ticket/AllTicket.aspx");
        }

        private void saveComment()
        {
            ticket.TicketStatusId = 2;

            StaffBus staffBus = new StaffBus();
            Core.Entity.Staff staff = staffBus.getStaffByUserId(Convert.ToInt32(Session["User"]));

            Core.Entity.TicketComment comment = new Core.Entity.TicketComment();
            comment.Content = txtContent.Text;
            comment.TicketId = ticket.Id;
            comment.ParentId = staff.Id;
            comment.ParentType = "STAFFS";
            DateTime timeStamp = DateTime.Now;
            comment.Attachment1 = this.saveAttachment(timeStamp, txtFile1.PostedFile);
            comment.Attachment2 = this.saveAttachment(timeStamp, txtFile2.PostedFile);
            comment.Attachment3 = this.saveAttachment(timeStamp, txtFile3.PostedFile);

            if (!commentBus.insert(comment))
            {
                String script = "alert('Không gửi được yêu cầu, vui lòng thử lại!');";
                ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", script, true);
            }
            else
            {
                Response.Redirect("/Ticket/TicketEdit.aspx?id=" + ticket.Id, true);
            }
        }

        private String saveAttachment(DateTime timeStamp, HttpPostedFile file)
        {
            String fileName = "";
            if (file != null && file.FileName != "")
            {
                try
                {
                    String imageName = timeStamp.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + file.FileName;
                    file.SaveAs(Server.MapPath("/Assets/data/" + imageName));
                    fileName = imageName;
                }
                catch (Exception ex) { }
            }
            return fileName;
        }

        protected void btnAddComment_Click(object sender, EventArgs e)
        {
            this.saveComment();
        }

    }
}